<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
}
</route>

<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <wd-navbar title="城市设施报修" fixed placeholder safeAreaInsetTop>
      <template #right>
        <wd-icon name="search" size="18" color="#fff" />
      </template>
    </wd-navbar>

    <!-- 主要功能区 -->
    <view class="main-action px-4 py-12">
      <view class="text-center mb-6">
        <text class="text-xl text-gray-700">
          {{ role === 2 ? '有新的设施需要添加？' : '发现损坏的公共设施？' }}
        </text>
      </view>
      <view class="action-button-wrapper">
        <wd-button type="primary" size="large" block @click="handleMapRepair">
          <template #default>
            <view class="flex items-center justify-center">
              <wd-icon name="location" size="20" />
              <text class="ml-2">{{ role === 2 ? '去添加' : '地图选点报修' }}</text>
            </view>
          </template>
        </wd-button>
      </view>
    </view>

    <!-- 最近报修 -->
    <view class="recent-repairs px-4" v-if="role === 1">
      <view class="flex justify-between items-center mb-2">
        <text class="text-lg font-bold">最近报修</text>
        <text class="text-sm text-blue-500" @click="handleRepairViewMore">
          {{ showAllRepair ? '收起' : '查看更多' }}
        </text>
      </view>
      <wd-cell-group border>
        <wd-cell
          v-for="(item, index) in showAllRepair ? recentRepairs : recentRepairs.slice(0, 2)"
          :key="index"
          :title="`描述: ${item.description}`"
          @click="handleRepairClick(item)"
          clickable
        >
          <template #label>
            <view class="text-gray-400 text-xs" style="width: 200px">
              <view>报修时间: {{ item.createTime }}</view>
              <view v-if="item.handlerName">
                处理人: {{ item.handlerName }} {{ item.handlerPhone }}
              </view>
              <view v-if="item.finishTime">完成时间: {{ item.finishTime }}</view>
            </view>
          </template>
          <template #default>
            <wd-tag
              :type="item.status === 1 ? 'warning' : item.status === 2 ? 'primary' : 'success'"
            >
              {{ item.status === 1 ? '待处理' : item.status === 2 ? '处理中' : '已完成' }}
            </wd-tag>
          </template>
        </wd-cell>
      </wd-cell-group>
    </view>

    <!-- 附近设施 -->
    <view class="nearby-facilities mt-4 px-4 pb-4">
      <view class="flex justify-between items-center mb-2">
        <text class="text-lg font-bold">附近设施</text>
        <text class="text-sm text-blue-500" @click="handleViewMore">
          {{ showAllFacilities ? '收起' : '查看更多' }}
        </text>
      </view>
      <view class="grid grid-cols-2 gap-3">
        <view
          v-for="(item, index) in showAllFacilities ? facilityList : facilityList.slice(0, 4)"
          :key="index"
          class="facility-card bg-white rounded-lg p-3 shadow-sm"
          @click="role === 1 ? handleFacilityClick(item) : undefined"
        >
          <view class="flex items-center">
            <text class="ml-2 text-base">{{ item.name }}</text>
          </view>
          <view class="text-xs text-gray-400 mt-2">{{ item.address }}</view>
          <view :class="['text-xs mt-1', item.status === 2 ? 'text-orange-500' : 'text-green-500']">
            {{ item.status === 2 ? '维修中' : '正常' }}
          </view>
          <view class="text-xs mt-1 text-gray-500">
            {{ item.deptName }}
          </view>
        </view>
      </view>
    </view>

    <!-- 维修人员 部门工单 -->
    <view class="recent-repairs px-4" v-if="role === 2">
      <view class="flex justify-between items-center mb-2">
        <text class="text-lg font-bold">部门工单</text>
        <text class="text-sm text-blue-500" @click="handleAllDepViewMore">
          {{ showAllDepartmentRepair ? '收起' : '查看更多' }}
        </text>
      </view>
      <wd-cell-group border>
        <wd-cell
          v-for="(item, index) in showAllDepartmentRepair ? depRepairs : depRepairs.slice(0, 2)"
          :key="index"
          :title="`描述: ${item.description}`"
          @click="handleRepairClick(item)"
          clickable
        >
          <template #label>
            <view class="text-gray-400 text-xs" style="width: 200px">
              <view>报修时间: {{ item.createTime }}</view>
              <view v-if="item.handlerName">
                处理人: {{ item.handlerName }} {{ item.handlerPhone }}
              </view>
              <view v-if="item.finishTime">完成时间: {{ item.finishTime }}</view>
            </view>
          </template>
          <template #default>
            <wd-tag
              :type="item.status === 1 ? 'warning' : item.status === 2 ? 'primary' : 'success'"
            >
              {{ item.status === 1 ? '待处理' : item.status === 2 ? '处理中' : '已完成' }}
            </wd-tag>
          </template>
        </wd-cell>
      </wd-cell-group>
    </view>

    <!-- 工单详情弹窗 -->
    <wd-popup
      v-model="showRepairDetail"
      position="bottom"
      :style="{ height: '75vh' }"
      class="rounded-t-xl"
    >
      <view class="p-4 pb-24">
        <view class="text-lg font-bold mb-4">工单详情</view>

        <!-- 工单信息 -->
        <view class="space-y-3">
          <view class="flex">
            <text class="text-gray-500 w-24">工单编号：</text>
            <text>{{ selectedRepair?.id }}</text>
          </view>

          <view class="flex">
            <text class="text-gray-500 w-24">报修描述：</text>
            <text>{{ selectedRepair?.description }}</text>
          </view>

          <view class="flex">
            <text class="text-gray-500 w-24">报修时间：</text>
            <text>{{ selectedRepair?.createTime }}</text>
          </view>
          <view class="flex" v-if="selectedRepair?.handlerName">
            <text class="w-24 text-gray-500">处理人：</text>
            <text>{{ selectedRepair?.handlerName }}</text>
          </view>
          <view class="flex" v-if="selectedRepair?.handlerPhone">
            <text class="w-24 text-gray-500">联系电话：</text>
            <text>{{ selectedRepair?.handlerPhone }}</text>
          </view>
          <view class="flex" v-if="selectedRepair?.finishTime">
            <text class="w-24 text-gray-500">完成时间：</text>
            <text>{{ selectedRepair?.finishTime }}</text>
          </view>
          <view class="flex">
            <text class="w-24 text-gray-500">当前状态：</text>
            <wd-tag
              :type="
                selectedRepair?.status === 1
                  ? 'warning'
                  : selectedRepair?.status === 2
                    ? 'primary'
                    : 'success'
              "
            >
              {{
                selectedRepair?.status === 1
                  ? '待处理'
                  : selectedRepair?.status === 2
                    ? '处理中'
                    : '已完成'
              }}
            </wd-tag>
          </view>
          <view v-if="selectedRepair?.imageUrl" class="mt-2 mb-32">
            <!-- 添加底部边距 -->
            <text class="text-gray-500 mb-2 block">故障图片：</text>
            <image
              :src="`http://localhost:8080${selectedRepair.imageUrl}`"
              mode="aspectFill"
              class="rounded-lg"
              style="width: 150rpx; height: 150rpx"
            />
          </view>

          <!-- 状态更新（仅维修人员可见且工单未完成） -->
          <view v-if="role === 2 && selectedRepair?.status !== 3" class="mt-4">
            <view class="border-t border-gray-200 pt-4">
              <view class="flex items-center mb-4">
                <text class="text-gray-500 w-24">更新状态：</text>
                <wd-radio-group v-model="selectedStatus" class="flex-1">
                  <wd-radio :value="2" :disabled="selectedRepair?.status === 2">处理中</wd-radio>
                  <wd-radio :value="3">已完成</wd-radio>
                </wd-radio-group>
              </view>
              <wd-button type="primary" block @click="handleUpdateStatus" :loading="updating">
                更新状态
              </wd-button>
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, computed } from 'vue'
import { getRecentRepair, getFacilityAll } from '@/service/index/foo'
import { useUserStore } from '@/store'
import { fetAllSheshi, fetchUpdateRepairStatus, fetDepAllRepair } from '@/service/repair'

const recentRepairs = ref([])
const depRepairs = ref([])
const facilityList = ref([])
const showAllFacilities = ref(false)
const showRepairDetail = ref(false)
const selectedRepair = ref<any>(null)
const userStore = useUserStore()
const showAllRepair = ref(false)
const showAllDepartmentRepair = ref(false)

// 使用计算属性获取最新的role和token
const role = computed(() => userStore.role)
const token = computed(() => userStore.token)

// 最近报修
const getRecentRepairList = async () => {
  try {
    const res: any = await getRecentRepair(1, 1000)
    recentRepairs.value = res.data.records
    // console.log('获取最近报修成功:', recentRepairs.value)
  } catch (error) {
    console.error('获取最近报修失败:', error)
    uni.showToast({
      title: '获取最近报修失败',
      icon: 'none',
    })
  }
}

/* 维修人员查看当前部门的工单 */
const getDepRepairList = async () => {
  try {
    const res: any = await fetDepAllRepair()
    depRepairs.value = res.data.records
    // console.log('获取部门工单成功:', depRepairs.value)
  } catch (error) {
    console.error('获取部门工单失败:', error)
    uni.showToast({
      title: '获取部门工单失败',
      icon: 'none',
    })
  }
}
// 查看更多报修
const handleRepairViewMore = () => {
  showAllRepair.value = !showAllRepair.value
}

const handleAllDepViewMore = () => {
  showAllDepartmentRepair.value = !showAllDepartmentRepair.value
}

// 检查登录状态
const checkLoginStatus = () => {
  if (!token.value) {
    console.log('未登录，跳转到登录页面')
    uni.navigateTo({
      url: '/pages/auth/index',
    })
    return false
  }
  return true
}

// 附近设施
const getFacilityList = async () => {
  try {
    // 根据角色获取不同的设施列表
    const res: any = role.value === 1 ? await getFacilityAll() : await fetAllSheshi()
    facilityList.value = role.value === 1 ? res.data : res.data.records
    // console.log('获取设施列表成功:', facilityList.value)
  } catch (error) {
    console.error('获取设施列表失败:', error)
    uni.showToast({
      title: '获取设施列表失败',
      icon: 'none',
    })
  }
}

// 初始化数据
const initData = async () => {
  if (checkLoginStatus()) {
    console.log('开始加载数据，当前角色:', role.value)
    try {
      // 显示加载提示
      uni.showLoading({
        title: '加载中...',
      })

      // 根据角色初始化数据
      if (role.value === 1) {
        await getRecentRepairList()
      } else {
        await getDepRepairList()
      }
      await getFacilityList()

      console.log('数据加载完成')
    } catch (error) {
      console.error('数据加载失败:', error)
    } finally {
      // 隐藏加载提示
      uni.hideLoading()
    }
  }
}

// 页面加载时检查登录状态并初始化数据
onMounted(() => {
  initData()
})

// 每次进入页面时重新加载数据
onShow(() => {
  console.log('页面显示，重新加载数据')
  if (token.value) {
    initData()
  }
})

// 监听token和role变化
watch([() => userStore.token, () => userStore.role], () => {
  console.log('用户信息变化，token:', token.value, '角色:', role.value)
  if (token.value) {
    initData()
  } else {
    checkLoginStatus()
  }
})

// 查看更多设施
const handleViewMore = () => {
  showAllFacilities.value = !showAllFacilities.value
}

// 点击设施
const handleFacilityClick = (facility: any) => {
  if (facility.status === 2) {
    uni.showToast({
      title: '该设施正在维修中',
      icon: 'none',
    })
    return
  }

  // 跳转到报修页面
  uni.navigateTo({
    url: `/pages/submit/index?facilityId=${facility.id}&facilityName=${facility.name}&facilityAddress=${facility.address}`,
  })
}

// 地图报修
const handleMapRepair = () => {
  uni.navigateTo({
    url: role.value === 2 ? '/pages/repair/add/index' : '/pages/map/index',
  })
}

// 点击工单卡片
const handleRepairClick = (repair: any) => {
  selectedRepair.value = repair
  showRepairDetail.value = true
}

// 在script部分添加
const selectedStatus = ref(2)
const updating = ref(false)

// 更新工单状态
const handleUpdateStatus = async () => {
  if (!selectedRepair.value || !selectedStatus.value) return

  try {
    updating.value = true
    await fetchUpdateRepairStatus({
      orderId: selectedRepair.value.id,
      status: selectedStatus.value,
    })

    uni.showToast({
      title: '状态更新成功',
      icon: 'success',
    })

    // 关闭弹窗并刷新列表
    showRepairDetail.value = false
    getDepRepairList()
  } catch (error) {
    console.error('更新工单状态失败:', error)
    uni.showToast({
      title: '更新状态失败',
      icon: 'error',
    })
  } finally {
    updating.value = false
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-action {
  background: linear-gradient(to bottom, #1989fa, #ffffff);
}

.facility-card {
  border: 1px solid #eee;
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
  }
}

:deep(.wd-navbar) {
  background-color: #1989fa !important;
}

:deep(.wd-grid-item) {
  padding: 16px 0;
}

:deep(.wd-cell-group) {
  overflow: hidden;
  border-radius: 8px;
}

:deep(.wd-popup) {
  border-radius: 16px 16px 0 0;
}
</style>
